# @shuaige : 陈世玉
# @name :Cars_Spider.py.py
# @time :2024/12/9 09:47
import requests
import json
import csv
def get_data(i):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
    }
    if i < 10:
        url = "https://cars.app.autohome.com.cn/carext/recrank/all/getrecranklistpageresult2?from=28&pm=2&pluginversion=11.65.0&model=1&channel=0&pageindex=1&pagesize=50&typeid=1&subranktypeid=1&levelid=0&price=0-9000&date=2024-0" + str(
            i)
    else:
        url = "https://cars.app.autohome.com.cn/carext/recrank/all/getrecranklistpageresult2?from=28&pm=2&pluginversion=11.65.0&model=1&channel=0&pageindex=1&pagesize=50&typeid=1&subranktypeid=1&levelid=0&price=0-9000&date=2024-" + str(
            i)
    response = requests.get(url, headers=headers)
    text = response.text
    # 将其转化为json数据
    text = json.loads(text)
    return text
def parse_data(j, text):
    data = text['result']['list']
    with open('data.csv', 'a', encoding='utf-8', newline='') as f:
        csvwriter = csv.writer(f)
        if j == 5:
            csvwriter.writerow(['月份', '排名', '车系', '价格', '销量', '排名变化', '评分'])
        for i in data:
            # 写入csv文件
            csvwriter.writerow(
                ["2024-" + str(j), i['rank'], i['seriesname'], i['priceinfo'], i['salecount'], i['rankchange'],
                 i['scorevalue']])

            print(i['rank'], end=' ')
            print(i['seriesname'], end=' ')
            print(i['priceinfo'], end=' ')
            print(i['salecount'], end=' ')
            print(i['rankchange'], end=' ')
            print(i['scorevalue'])
            print()
for i in range(5, 12):
    parse_data(i, get_data(i))